from django.db.models import Count
from cmdb.models import Host, DataBase, Tag

from .models import CLOUD


def get_cloud_asset_count():
    """
    获取不同云的资产数量
    :return:
    """
    hosts = Host.objects.values_list('public_cloud').annotate(Count('id'))
    #print(hosts)
    dbs = DataBase.objects.values_list('public_cloud').annotate(Count('id'))
    #print(dbs)

    # 初始化
    init_data = dict()
    for item in CLOUD:
        init_data[item[0]] = 0

    for key in init_data:
        for host in hosts:
            if key == host[0]:
                init_data[key] += host[1]
                break
        for db in dbs:
            if key == db[0]:
                init_data[key] += db[1]
                break

    data = []
    #print(init_data)
    for key in init_data:
        row = dict()
        for cloud in CLOUD:
            if key == cloud[0]:
                row['name'] = cloud[1]
                row['value'] = init_data[key]
                data.append(row)
                break
    print(data)
    return data


def get_each_type_asset_count():
    """
    获取各类型资产占比
    :return:
    """
    host_count = Host.objects.count()
    db_count = DataBase.objects.count()
    data = [
        {'name': '服务器', 'value': host_count},
        {'name': 'RDS', 'value': db_count},
    ]
    print(data)
    return data

def get_business_line_host_nums():
    """
    获取各个业务线的主机数量
    :return:
    """
    tags = Tag.objects.filter(type__name="business")
    print(tags)
    data = []
    data = [{'name': tag.name_cn, 'value': tag.host_set.count()} for tag in tags]
    print(data)
    return data


def get_tag_cloud():
    """
    标签云
    :return:
    """
    tags = Tag.objects.all()
    data = [{'text': tag.name_cn, 'weight': tag.host_set.count(),
             'link': '/cmdb/hosts/?tag={}'.format(tag.name)} for tag in tags]
    print(data)
    return data


def assets_overview():
    """
    资产管理，总览页数据
    :return:
    """
    clouds_asset_count = get_cloud_asset_count()
    each_type_assets_count = get_each_type_asset_count()
    business_line_host_nums = get_business_line_host_nums()
    tag_cloud = get_tag_cloud()

    return {'clouds_asset_count': clouds_asset_count,
            'each_type_assets_count': each_type_assets_count,
            'business_line_host_nums': business_line_host_nums,
            'tag_cloud': tag_cloud}

